from qcloud_cos import CosConfig, CosServiceError
from qcloud_cos import CosS3Client


# import sys
# import logging
#
# logging.basicConfig(level=logging.INFO, stream=sys.stdout)


class CosTencent:
    def __init__(self):
        self.secret_id = 'AKIDYu1rQikVyA6lAI9k35qMbYEenfFYb3F9'  #
        self.secret_key = 'f28ycz4sPfeLlvoQlqeAPO6XhaCXaMs7'  #
        self.region = 'ap-beijing'
        self.config = CosConfig(Region=self.region, SecretId=self.secret_id, SecretKey=self.secret_key)
        self.client = CosS3Client(self.config)

    def create_bucket(self, bucket_name):
        """

        :param bucket_name: 桶名称-appid for example：examplebucket-1250000000
        :return:
        """
        result = {'status': True}
        try:
            response = self.client.create_bucket(
                Bucket=bucket_name
            )
            result['status'] = True
        except CosServiceError:
            result['status'] = False
        finally:
            return result

    def delete_bucket(self, bucket_name):
        result = {'status': True}
        try:
            response = self.client.delete_bucket(
                Bucket=bucket_name
            )
            result['status'] = True
        except CosServiceError:
            result['status'] = False
        finally:
            return result

    def browse_bucket(self):
        """
        bucket_list格式：
                {'Owner':
                    {'ID': 'qcs::cam::uin/100011758814:uin/100011758814',
                    'DisplayName': '100011758814'},
                'Buckets':
                    {'Bucket':
                        [
                        {'Name': 'test1-1300450009',
                          'Location': 'ap-beijing',
                          'CreationDate': '2022-05-12T05:33:13Z',
                          'BucketType': 'cos'},
                        ]
                    }
                }
        """
        bucket_list = self.client.list_buckets()
        return bucket_list

    def upload(self, bucket_name, key, image_object):
        self.client.upload_file_from_buffer(
            Bucket=bucket_name,
            Key=key,
            Body=image_object
        )

    def download(self):
        pass


if __name__ == '__main__':
    cos = CosTencent()
    # res = cos.delete_bucket('examplebucket-1300450009')
    cos.create_bucket('test1-1300450009')
    cos.browse_bucket()
    # print()
